package com.xxx.springboot.controller;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.xxx.springboot.listener.SystemListener;
import com.xxx.springboot.pojo.entity.User;
import com.xxx.springboot.service.UserService;

/**
 * 测试 sentinel限流 Controller
 */
@Controller
@RequestMapping(value = "/sentinel", produces = "application/json;charset=utf-8")
public class TestSentinelController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(TestSentinelController.class);

	@Autowired
	private UserService userService;
	
	/**
	 * guava cache 
	 */
	private LoadingCache<String, User> userCache = CacheBuilder.newBuilder()
														.maximumSize(1000)	// 最多1000个对象
														.expireAfterWrite(10, TimeUnit.SECONDS)	 // 写入后存活时间：10秒
														.expireAfterAccess(60, TimeUnit.SECONDS) // 访问后过期时间：60秒
														.build(new CacheLoader<String, User>(){
											
															@Override
															public User load(String userId) throws Exception {
																return userService.getById(userId);
															}
															
														});
	/**
     * 系统启动时间戳
     */
    @RequestMapping("/versionNo")
    @ResponseBody
    public String versionNo(){
    	logger.info("enter method versionNo().");
        return SystemListener.versionNo;
    }

    /**
     * 测试guavacache
     * @param userId
     * @return
     * @throws ExecutionException 
     */
    @RequestMapping("/testGuavaCache")
    @ResponseBody
    public User testGuavaCache(String userId) throws ExecutionException {
        System.out.println("测试guavaCache");
        User user = userCache.get(userId);
        return user;
    }
    
}
